<template>
  <div class="home">
    <div class="post-actions" v-if="isLoggedIn">
      <el-button type="primary" @click="showCreatePostDialog">发布新帖子</el-button>
    </div>

    <el-dialog v-model="createPostDialogVisible" title="发布新帖子" width="50%">
      <el-form :model="newPost" :rules="postRules" ref="postForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="newPost.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input type="textarea" v-model="newPost.content" rows="4" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="createPostDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCreatePost" :loading="posting">发布</el-button>
        </span>
      </template>
    </el-dialog>

    <div class="posts-list">
      <el-card v-for="post in posts" :key="post.id" class="post-card">
        <template #header>
          <div class="post-header">
            <h3 class="post-title" @click="viewPostDetail(post.id)">{{ post.title }}</h3>
            <div class="post-meta">
              <span>作者: {{ post.author }}</span>
              <span>{{ formatDate(post.createTime) }}</span>
            </div>
          </div>
        </template>
        <div class="post-content">{{ post.content }}</div>
        <div class="post-footer">
          <el-button type="text" @click="handleLike(post)" :class="{ 'liked': post.liked }">
            <el-icon><ThumbsUp /></el-icon> {{ post.likes || 0 }}
          </el-button>
          <el-button type="text" @click="viewPostDetail(post.id)">
            <el-icon><ChatLineRound /></el-icon> {{ post.comments || 0 }}
          </el-button>
        </div>
      </el-card>

      <div v-if="posts.length === 0" class="no-posts">
        暂无帖子
      </div>

      <el-pagination
        v-if="total > 0"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { ThumbsUp, ChatLineRound } from '@element-plus/icons-vue'

export default {
  name: 'HomePage',
  components: {
    ThumbsUp,
    ChatLineRound
  },
  data() {
    return {
      posts: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      isLoggedIn: false,
      createPostDialogVisible: false,
      posting: false,
      newPost: {
        title: '',
        content: ''
      },
      postRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' },
          { min: 2, max: 1000, message: '长度在 2 到 1000 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.checkLoginStatus()
    this.fetchPosts()
  },
  methods: {
    checkLoginStatus() {
      const token = localStorage.getItem('token')
      this.isLoggedIn = !!token
    },
    async fetchPosts() {
      try {
        const response = await axios.get(`/api/posts?page=${this.currentPage - 1}&size=${this.pageSize}`)
        this.posts = response.data.content
        this.total = response.data.totalElements
      } catch (error) {
        ElMessage.error('获取帖子列表失败')
      }
    },
    formatDate(date) {
      return new Date(date).toLocaleString()
    },
    showCreatePostDialog() {
      this.createPostDialogVisible = true
    },
    async handleCreatePost() {
      try {
        await this.$refs.postForm.validate()
        this.posting = true
        await axios.post('/api/posts', this.newPost)
        ElMessage.success('发布成功')
        this.createPostDialogVisible = false
        this.newPost.title = ''
        this.newPost.content = ''
        this.fetchPosts()
      } catch (error) {
        ElMessage.error(error.response?.data?.message || '发布失败')
      } finally {
        this.posting = false
      }
    },
    async handleLike(post) {
      if (!this.isLoggedIn) {
        this.$router.push('/login')
        return
      }
      try {
        await axios.post(`/api/posts/${post.id}/like`)
        post.liked = !post.liked
        post.likes = post.liked ? (post.likes || 0) + 1 : (post.likes || 1) - 1
      } catch (error) {
        ElMessage.error('操作失败')
      }
    },
    viewPostDetail(postId) {
      this.$router.push(`/post/${postId}`)
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchPosts()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchPosts()
    }
  }
}
</script>

<style scoped>
.home {
  max-width: 800px;
  margin: 0 auto;
}

.post-actions {
  margin-bottom: 20px;
  text-align: right;
}

.post-card {
  margin-bottom: 20px;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.post-title {
  margin: 0;
  cursor: pointer;
  color: #409EFF;
}

.post-title:hover {
  text-decoration: underline;
}

.post-meta {
  font-size: 14px;
  color: #909399;
}

.post-meta span {
  margin-left: 10px;
}

.post-content {
  margin: 10px 0;
  color: #606266;
}

.post-footer {
  margin-top: 10px;
  display: flex;
  gap: 20px;
}

.liked {
  color: #409EFF;
}

.no-posts {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.el-pagination {
  margin-top: 20px;
  justify-content: center;
}
</style> 